package cn.legend.travel.tour.team.service.impl;

import cn.legend.travel.common.enumerator.ServiceCode;
import cn.legend.travel.common.exception.ServiceException;
import cn.legend.travel.tour.team.dao.cache.IOrderInfoCacheRepository;
import cn.legend.travel.tour.team.dao.persist.repository.IOrderRepository;
import cn.legend.travel.tour.team.pojo.entity.Order;
import cn.legend.travel.tour.team.pojo.entity.TravelersInfo;
import cn.legend.travel.tour.team.pojo.param.OrderInfoParam;
import cn.legend.travel.tour.team.pojo.param.OrderParam;
import cn.legend.travel.tour.team.pojo.po.OrderInfoPO;
import cn.legend.travel.tour.team.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

@Service
public class OrderServiceImpl implements IOrderService {
    @Autowired
    private IOrderRepository orderRepository;
    @Autowired
    private IOrderInfoCacheRepository orderInfoCacheRepository;
    @Override
    public void createOrder(OrderParam orderParam) {
        if(orderParam.getUserId() == null || orderParam.getProductId() == null ){
            throw new ServiceException(ServiceCode.ERROR_BAD_REQUEST,"请求参数有误");
        }
        //数据库中还差相关的数据字段,有些功能是无法完成的
        Order order = new Order();
        order.setId(orderParam.getOrderId());
        order.setProductId(Long.parseLong(orderParam.getProductId()));
        order.setUserId(Long.parseLong(orderParam.getUserId()));
        order.setState(0);
        order.setProductCount(1);
        orderRepository.createOrder(order);
    }

    @Override
    public void saveOrderInfo(OrderInfoParam orderInfoParam) {
        OrderInfoPO orderInfoPO = new OrderInfoPO();
        List<TravelersInfo> travelersInfos = orderInfoParam.getTravelersInfos();

        if(CollectionUtils.isEmpty(travelersInfos)){
            orderInfoPO.setTravelersInfos(null);
        }else{
            List<TravelersInfo> orderInfoPOList = new ArrayList<>();
            travelersInfos.stream().filter(travelersInfo -> !"".equals(travelersInfo.getName())
                    && !"".equals(travelersInfo.getPhone())
                    &&"".equals(travelersInfo.getIDCard())
            ).forEach(orderInfoPOList::add);
            orderInfoPO.setTravelersInfos(orderInfoPOList);
        }

        orderInfoPO.setOrderNo(orderInfoParam.getOrderNo());
        orderInfoPO.setBookerInfo(orderInfoParam.getBookerInfo());

        orderInfoCacheRepository.setOrderInfo(orderInfoPO);
    }

    @Override
    public OrderInfoPO getOrderInfoByOrderNo(String orderNo) {

        return orderInfoCacheRepository.getOrderInfoByOrderNo(orderNo);
    }
}

